//
//  CarBrandViewController.m
//  huisaoche
//
//  Created by 谭谭伟 on 2017/8/16.
//  Copyright © 2017年 Minidai. All rights reserved.
//

#import "MNDCarBrandViewController.h"
#import "MJExtension.h"
#import "MNDCarBrandModel.h"
#import "MNDCarBrandTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "MNDAssessWebViewController.h"

#define kCarBrandTableViewCell @"MNDCarBrandTableViewCell"
#define kTopMargin 23
#define kBottomViewHeight 58
#define kTopTypeHeight 45


@interface MNDCarBrandViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *topCollectionView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topCollectionViewHeight;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;

/* 第一个 */
@property (weak, nonatomic) IBOutlet UITableView *firstTableview;
/* 第二个 */
@property (strong, nonatomic) UITableView *secondTableview;
/* 第三个 */
@property (strong, nonatomic) UITableView *thirdTableview;

@property (strong, nonatomic) NSArray *cityList; //城市列表

/* 第一个类型选择 */
@property (strong, nonatomic)  NSIndexPath *firstSelectIndex;
/* 第二个类型选择 */
@property (assign, nonatomic)  NSIndexPath  *secondSelectIndex;

/* 一级字典 */
@property (strong, nonatomic) NSDictionary *jsonDict;
/* 一级json数组 */
@property (strong, nonatomic) NSArray *jsonArray;
/* 二级字典 */
@property (strong, nonatomic) NSDictionary *seriesDict;
@property (strong, nonatomic) NSArray *seriesArray;

/* 模型数组 */
@property (strong, nonatomic) NSMutableArray <MNDCarBrandModel *> *carTypeModelArray;
/* 索引栏数组 */
@property (strong, nonatomic) NSMutableArray *indexArray;

/* 第一个tableview选择的label */
@property (strong, nonatomic) UILabel *firstSelectLabel;
/* 第二个tableview选择的label */
@property (strong, nonatomic) UILabel *secondSelectLabel;

/* 热门品牌view高度 */
@property (assign, nonatomic) CGFloat topViewHeight;
/* 热门品牌模型数组 */
@property (strong, nonatomic) NSMutableArray *hotModelArray;


@end

@implementation MNDCarBrandViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.firstTableview.rowHeight = UITableViewAutomaticDimension;
    self.firstTableview.estimatedRowHeight = 44;
    
    [self setupUI];

    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.title = @"车型选择";
    //设置右侧索引栏属性
    self.firstTableview.sectionIndexColor = [UIColor blueColor];
    self.firstTableview.sectionIndexBackgroundColor = [UIColor clearColor];
}

#pragma mark -懒加载
- (NSMutableArray<MNDCarBrandModel *> *)carTypeModelArray {
    if (!_carTypeModelArray) {
        _carTypeModelArray = [NSMutableArray array];
    }
    return _carTypeModelArray;
}

- (NSMutableArray *)indexArray {
    if (!_indexArray) {
        _indexArray = [NSMutableArray array];
    }
    return _indexArray;
}

- (NSMutableArray *)hotModelArray {
    if (!_hotModelArray) {
        _hotModelArray = [NSMutableArray array];
    }
    return _hotModelArray;
}



#pragma mark -搭建界面
- (void)setupUI {
    
    //布局collectionView
    _flowLayout.itemSize = CGSizeMake(kScreenWidth*0.2, 86);
    _flowLayout.minimumInteritemSpacing = 0;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
//    self.topCollectionView
    //Cache目录
    kdeclare_weakself;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:@"car_list.json"];
    if(!filePath) {
        NSLog(@"文件未找到");
    }else {
        //加载JSON文件
        dispatch_queue_t queue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        dispatch_async(queue, ^{
            //加载JSON文件
            NSData *data = [NSData dataWithContentsOfFile:filePath];
            NSError *error;
            if (data) {
                weakSelf.jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
                
                weakSelf.carTypeModelArray = [MNDCarBrandModel mj_objectArrayWithKeyValuesArray:weakSelf.jsonArray];
                weakSelf.indexArray = [NSMutableArray array];
                for (MNDCarBrandModel *model in weakSelf.carTypeModelArray) {
                    [weakSelf.indexArray addObject:model.brand_initial];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.firstTableview reloadData];
                });
            }
            
        });
        
    }
    
    // -------- 一级tabview --------
//    _firstTableview = [[UITableView alloc]initWithFrame:CGRectMake(0, _topViewHeight, kScreenWidth, kScreenHeight - _topViewHeight - kTopTypeHeight) style:UITableViewStylePlain];
    _firstTableview.dataSource = self;
    _firstTableview.delegate = self;
    _firstTableview.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_firstTableview];
    
    // -------- 二级tabview --------
    _secondTableview = [[UITableView alloc]initWithFrame:CGRectMake(kScreenWidth, _isHaveNav == YES ? 64:0, kScreenWidth , kScreenHeight - kTopTypeHeight - 64) style:UITableViewStylePlain];
    _secondTableview.dataSource = self;
    _secondTableview.delegate = self;
    _secondTableview.tableFooterView = [[UIView alloc]init];

    [self.view addSubview:_secondTableview];
    
//    // -------- 三级tabview --------
    _thirdTableview = [[UITableView alloc]initWithFrame:CGRectMake(kScreenWidth,0, kScreenWidth*0.5, kScreenHeight - kTopTypeHeight -64) style:UITableViewStylePlain];
    _thirdTableview.dataSource = self;
    _thirdTableview.delegate = self;
    [self.view addSubview:_thirdTableview];
    
}


- (void)configCarType:(NSArray *)modelArray {
    //    self.carTypeModel = [FirstCarTypeModel mj_objectWithKeyValues:modelArray];
    //    NSLog(@"%@",_carTypeModel);
    
}

#pragma mark -UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([tableView isEqual:_firstTableview]) {
        return _carTypeModelArray.count;
    }else if([tableView isEqual:_secondTableview]){
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        return secondeModelArray.count;
    }else {
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        SecondCarTypeModel *secondModel = secondeModelArray[_secondSelectIndex.section];
        NSArray *thirdmodelArray = secondModel.serie;
        ThirdCarTypeModel *thirdModel = thirdmodelArray[_secondSelectIndex.row];
        NSArray *yearModelArray = thirdModel.models;
        return yearModelArray.count;
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if ([tableView isEqual:_firstTableview]) {
        MNDCarBrandModel *model = _carTypeModelArray[section];
        
        return model.brands.count;
    }else if ([tableView isEqual:_secondTableview]){
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        SecondCarTypeModel *secondModel = secondeModelArray[section];
        return secondModel.serie.count;
    }else {
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        SecondCarTypeModel *secondModel = secondeModelArray[_secondSelectIndex.section];
        NSArray *thirdmodelArray = secondModel.serie;
        ThirdCarTypeModel *thirdModel = thirdmodelArray[_secondSelectIndex.row];
        NSArray *yearModelArray = thirdModel.models;
        YearCarTypeModel *yearModel = yearModelArray[section];
        return yearModel.model.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_firstTableview]) {
        
        MNDCarBrandTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCarBrandTableViewCell];
        if (cell == nil) {
            cell = [[MNDCarBrandTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCarBrandTableViewCell];
        }
        MNDCarBrandModel *model = _carTypeModelArray[indexPath.section];
        FirstCarTypeModel *firstModel = model.brands[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        cell.titleLabel.numberOfLines = 0;
//        cell.titleLabel.font = [UIFont systemFontOfSize:14];
//        cell.titleLabel.textColor = kColorBlack;
        cell.titleLabel.text = firstModel.brand_name;
       
        [cell.logoImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",@"http://devapi.bylongma.com",firstModel.brand_logo]] placeholderImage:nil];
        NSLog(@"图片：%@%@",API_BASE_URL,firstModel.brand_logo);
//        cell.imageView.image = [UIImage imageNamed:@"app_share_cell_icon"];
        return cell;
    }else if ([tableView isEqual:_secondTableview]) {
        static NSString *mainCellId = @"secondCellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mainCellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mainCellId];
        }
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        SecondCarTypeModel *secondModel = secondeModelArray[indexPath.section];
        NSArray *thirdmodelArray = secondModel.serie;
        ThirdCarTypeModel *thirdModel = thirdmodelArray[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.textColor = kColorBlack;
        cell.textLabel.text = thirdModel.series_name;
        return cell;
        
    }else {
        static NSString *mainCellId = @"thirdCellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:mainCellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:mainCellId];
        }
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        SecondCarTypeModel *secondModel = secondeModelArray[_secondSelectIndex.section];
        NSArray *thirdmodelArray = secondModel.serie;
        ThirdCarTypeModel *thirdModel = thirdmodelArray[_secondSelectIndex.row];
        NSArray *yearModelArray = thirdModel.models;
        YearCarTypeModel *yearCarModel = yearModelArray[indexPath.section];
        NSArray *modelArray = yearCarModel.model;
        ModelCarTypeModel *typeModel = modelArray[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = kColorBlack;
        cell.textLabel.text = typeModel.model_name;
        return cell;
        
    }
}



#pragma mark -UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    kdeclare_weakself;
    if ([tableView isEqual:_firstTableview]) {
        _firstSelectIndex = indexPath;
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.textLabel.textColor = kColorDarkOrange;
        _firstSelectLabel.textColor = kColorBlack;
        _firstSelectLabel = cell.textLabel;
        [self.secondTableview reloadData];
        
        [UIView animateWithDuration:0.25 animations:^{
            weakSelf.secondTableview.frame = CGRectMake(kScreenWidth*0.5, weakSelf.isHaveNav == YES ? 64:0, kScreenWidth*0.5, kScreenHeight - kTopTypeHeight - 64);
            weakSelf.thirdTableview.frame = CGRectMake(kScreenWidth, 0, kScreenWidth*0.5, kScreenHeight - kTopTypeHeight - 64);
        }];
    }else if ([tableView isEqual:_secondTableview]) {
        _secondSelectIndex = indexPath;
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.textLabel.textColor = kColorDarkOrange;
        _secondSelectLabel.textColor = kColorBlack;
        _secondSelectLabel = cell.textLabel;
        //车型回调
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        SecondCarTypeModel *secondModel = secondeModelArray[_secondSelectIndex.section];
        NSArray *thirdmodelArray = secondModel.serie;
        //车系
        ThirdCarTypeModel *thirdModel = thirdmodelArray[_secondSelectIndex.row];
        NSString *carType = thirdModel.series_name;
        NSLog(@"carType: %@",carType);
        NSInteger carTypeId = thirdModel.series_id.integerValue;
        if(self.carTypeBlock != nil) {
            _carTypeBlock(thirdModel.series_name,carTypeId);
        }
      

        [self.thirdTableview reloadData];
        [UIView animateWithDuration:0.25 animations:^{
            weakSelf.secondTableview.frame = CGRectMake(kScreenWidth*0.25, 0, kScreenWidth, kScreenHeight - kTopTypeHeight -64);
            weakSelf.thirdTableview.frame = CGRectMake(kScreenWidth*0.5, 0,kScreenWidth*0.5, kScreenHeight - kTopTypeHeight - 64);
        }];
    }else {
        //车型回调
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        SecondCarTypeModel *secondModel = secondeModelArray[_secondSelectIndex.section];
        NSArray *thirdmodelArray = secondModel.serie;
        ThirdCarTypeModel *thirdModel = thirdmodelArray[_secondSelectIndex.row];
        NSArray *yearModelArray = thirdModel.models;
        YearCarTypeModel *yearCarModel = yearModelArray[indexPath.section];
        NSArray *modelArray = yearCarModel.model;
        ModelCarTypeModel *typeModel = modelArray[indexPath.row];
        //        cell.textLabel.text = typeModel.model_name;
        NSString *carType = [NSString stringWithFormat:@"%@%@%@",firstModel.brand_name,thirdModel.series_name,typeModel.model_name];
        NSLog(@"carType: %@",carType);
        NSInteger carTypeId = typeModel.model_id.integerValue;
        if(self.carTypeBlock != nil) {
            _carTypeBlock(typeModel.model_name,carTypeId);
        }
        
        //估值
        MNDAssessWebViewController *assessVC = [[MNDAssessWebViewController alloc] init];
        assessVC.title = @"车辆估值";
        NSString *url = [NSString stringWithFormat:@"%@?car_id=%zd&car_name=%@&city_id=%zd&city_name=%@",API_CAR_ASSESS,carTypeId,typeModel.model_name,self.cityAddressId,self.cityName];
        assessVC.webViewUrl = url;
        assessVC.cityAddressId = self.cityAddressId;
        assessVC.cityName = self.cityName;
        assessVC.isClearStack = YES;
        if (_isWebEnter) {
            NSDictionary *dict = @{
                                   @"car_id":@(carTypeId),
                                   @"car_name":typeModel.model_name
                                   };
            //发送通知刷新网页
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateWeb" object:dict];
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            [self.navigationController pushViewController:assessVC animated:YES];
        }
        
 
    }
}

//组标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if ([tableView isEqual:_firstTableview]) {
        return _carTypeModelArray[section].brand_initial;
    }else if ([tableView isEqual:_secondTableview]){
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        SecondCarTypeModel *secondeModel = secondeModelArray[section];
        return secondeModel.series_group_name;
    }else {
        MNDCarBrandModel *model = _carTypeModelArray[_firstSelectIndex.section];
        FirstCarTypeModel *firstModel = model.brands[_firstSelectIndex.row];
        NSArray *secondeModelArray = firstModel.series;
        SecondCarTypeModel *secondModel = secondeModelArray[_secondSelectIndex.section];
        NSArray *thirdmodelArray = secondModel.serie;
        ThirdCarTypeModel *thirdModel = thirdmodelArray[_secondSelectIndex.row];
        NSArray *yearModelArray = thirdModel.models;
        YearCarTypeModel *yearCarModel = yearModelArray[section];
        return yearCarModel.model_year;
    }
}

//设置组头文字颜色及背景颜色
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section

{
    
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    
    header.textLabel.textColor = kColorLightGray;
    header.textLabel.font = [UIFont systemFontOfSize:12];
    header.contentView.backgroundColor = kColorLightGrayLine;
    
}

//组头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 22;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}


//索引栏标题
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if([tableView isEqual:_firstTableview]){
        
        return _indexArray;
    }else {
        return nil;
    }
}

- (NSInteger )tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    kdeclare_weakself;
    if([scrollView isEqual:_firstTableview]) {
        [UIView animateWithDuration:0.25 animations:^{
            weakSelf.secondTableview.frame = CGRectMake(kScreenWidth, weakSelf.isHaveNav == YES ? 64:0, kScreenWidth*0.5, kScreenHeight - kTopTypeHeight -64);
//            _thirdTableview.frame = CGRectMake(kScreenWidth, 0, kScreenWidth*0.5, kScreenHeight - kTopTypeHeight -64);
        }];
    
    }else if ([scrollView isEqual:_secondTableview]) {
        [UIView animateWithDuration:0.25 animations:^{
//           _thirdTableview.frame = CGRectMake(kScreenWidth, 0, kScreenWidth*0.5, kScreenHeight - kTopTypeHeight -64);
        }];
    }else {
    
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
